package com.dnb.webmash.playmaker.client.ui;

import java.util.ArrayList;
import com.dnb.webmash.playmaker.client.AppConstants;
import com.dnb.webmash.playmaker.client.WebPlaylistService;
import com.dnb.webmash.playmaker.client.WebPlaylistServiceAsync;
import com.dnb.webmash.playmaker.client.mediaplayer.MediaPlayer;
import com.dnb.webmash.playmaker.client.mediaplayer.MediaPlayersManager;
import com.dnb.webmash.playmaker.shared.Option;
import com.dnb.webmash.playmaker.shared.PlayerConfig;
import com.dnb.webmash.playmaker.shared.PlayerType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

public class MyPlayerTab extends Composite {
	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);	
	private final WebPlaylistServiceAsync webPlaylistService = GWT.create(WebPlaylistService.class);
	private MediaPlayersManager mediaPlayersManager;
	private final Label errorLabel = new Label();	
	private final Label errorLabel_2 = new Label();
	private final CellTable<Option> configsCellTable = new CellTable<Option>();

	public MyPlayerTab(){
		/* END OF ADD MEDIA TAB
		 * START OF MYPLAYER TAB
		 */
		final DockLayoutPanel tab2_playerConfigDockLayoutPanel = new DockLayoutPanel(Unit.EM);

		HorizontalPanel horizontalPanel_2 = new HorizontalPanel();
		tab2_playerConfigDockLayoutPanel.addNorth(horizontalPanel_2, 2.0);

		final ListBox comboBox_2 = new ListBox(false);
		comboBox_2.setSelectedIndex(0);
		comboBox_2.setTitle(CONSTANTS.comboBox_2_title());
		//comboBox_2.addItem("");
		for (PlayerType t : PlayerType.values()){
			comboBox_2.addItem(t.name());
		}

		//Selecting a playertype in the combobox to see the user saved prefs or the player type defaults
		comboBox_2.addChangeHandler(new ChangeHandler(){
			@Override
			public void onChange(ChangeEvent event) {
				// TODO Auto-generated method stub
				int c = comboBox_2.getSelectedIndex()-1;//TODO FIGURE OUT WHY THE COMBOBOX RETURNS WRONG already working?
				errorLabel_2.setText("SELECTED :"+PlayerType.get(c));//TODO TESTING
				MyPlayerTab.this.requestLoadPlayerPrefsFromServer(PlayerType.get(c));
			}

		});
		horizontalPanel_2.add(comboBox_2);		

		CheckBox chckbxApplySettings = new CheckBox(CONSTANTS.chckbxApplySettings_text());
		chckbxApplySettings.setTitle(CONSTANTS.chckbxApplySettings_title());
		chckbxApplySettings.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				MyPlayerTab.this.mediaPlayersManager.enableSettings(event.getValue());
			}
		});
		horizontalPanel_2.add(chckbxApplySettings);
		//ADDING THIS LAST
		horizontalPanel_2.add(errorLabel_2);//TODO FIX THIS UI LOOKS BAD

		// Create name column.
		TextColumn<Option> nameColumn = new TextColumn<Option>() {
			@Override
			public String getValue(Option op) {
				return op.getMyName();
			}
		};
		//create values column.
		TextColumn<Option> valuesCol = new TextColumn<Option>() {
			@Override
			public String getValue(Option op) {
				String result="";
				ArrayList<String> optVals = op.getMyOptions();
				for (int i =0; i < optVals.size(); i++){
					result +="("+i+") "+ optVals.get(i);
					if (i !=optVals.size()-1)
						result +=", ";
				}
				return result;
			}
		};
		//create selected index colum.
		TextColumn<Option> selVal = new TextColumn<Option>() {
			@Override
			public String getValue(Option op) {
				return Integer.toString(op.getSetOption());
			}
		};

		configsCellTable.addColumn(nameColumn, "Name");
		configsCellTable.addColumn(valuesCol, "Possible Values");
		configsCellTable.addColumn(selVal, "Selected Value");

		tab2_playerConfigDockLayoutPanel.add(configsCellTable);
		configsCellTable.setSize("100%", "100%");

		this.initWidget(tab2_playerConfigDockLayoutPanel);
	}

	public void onLoad(){
		MediaPlayer curPlay = mediaPlayersManager.getCurrentPlayer();
		if (curPlay !=null){
			curPlay.getType().getValue();						

			if (mediaPlayersManager.hasPrefs()){
				errorLabel_2.setText("Current Preferences for "+curPlay.getType().toString());
				ArrayList<Option> currOpt = mediaPlayersManager.getCurrentOptions();
				MyPlayerTab.this.displayOpts(currOpt);							
			}
			else
			{
				configsCellTable.setRowCount(0,true);							
				MyPlayerTab.this.requestDefaultPrefsFromServer(curPlay.getType());//this calls displayopts only onsuccess													
			}
		}
		else errorLabel_2.setText("Select player from dropdown list");
	}

	@Override
	public void setWidth(String width) {//TODO add to prefs
		super.setWidth(width);
	}
	@Override
	public void setHeight(String height) {
		super.setHeight(height);
	}

	/*
	 * END OF MYPLAYER TAB
	 */

	//TODO create save playerprefs button and add UI	
	//This method is called everytime changes the playertype in the MyPlayer config tab.
	//@returns the defaultprefs for a playertype if the user doesnt have any saved PlayerConfigs
	private void requestLoadPlayerPrefsFromServer(PlayerType type) 
	throws IllegalArgumentException{
		this.webPlaylistService.requestLoadUserConfigs(type, new AsyncCallback<PlayerConfig>(){

			@Override
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				MyPlayerTab.this.errorLabel.setText("There was an error on the server... please try again later.");
			}

			@Override
			public void onSuccess(PlayerConfig result) {
				mediaPlayersManager.initSettings(result);
				MyPlayerTab.this.displayOpts(result.getOptions());
			}			
		});
		errorLabel_2.setText("Loading Preferences for "+type);
	}
	protected void displayOpts(ArrayList<Option> currOpt) {//three cols
		if (currOpt.size()>0){
			configsCellTable.setRowCount(currOpt.size(), true);					    
			configsCellTable.setRowData(0, currOpt);
			errorLabel_2.setText("Displaying Options.");//TODO TESTING
		}
		else errorLabel_2.setText("No Options to Display!");
	}
	//TODO add DEFAULTS button to UI to use this method (the combobox tries to load first)
	private void requestDefaultPrefsFromServer(PlayerType type)
	throws IllegalArgumentException {
		this.webPlaylistService.requestDefaultConfigs(type, new AsyncCallback<PlayerConfig>(){

			@Override
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				MyPlayerTab.this.errorLabel.setText("There was an error on the server... please try again later.");
			}

			@Override
			public void onSuccess(PlayerConfig result) {
				mediaPlayersManager.initSettings(result);
				MyPlayerTab.this.displayOpts(result.getOptions());
			}		
		});
		errorLabel_2.setText("Requesting Default Preferences for "+type);
	}

}